const OrdersPayRepository = require("../repositories/orderpayRepositories");

class OrdersPayService {
  handleResponse(data, error, notFoundMessage = "实体未找到") {
    if (error) {
      return {
        code: 1,
        msg: error.message,
        statusCode: error.statusCode || 500,
      };
    }
    if (!data) {
      return {
        code: 1,
        msg: notFoundMessage,
        statusCode: 404,
      };
    }
    return { code: 0, data: data };
  }

  async addNewOrder(orderData) {
    try {
      const newOrder = await OrdersPayRepository.addNewOrder(orderData);
      return this.handleResponse(newOrder, null, "添加失败");
    } catch (error) {
      return this.handleResponse(null, error, null);
    }
  }

  async deleteOrderById(id) {
    try {
      const result = await OrdersPayRepository.deleteOrderById(id);
      return this.handleResponse(result ? "删除成功" : null, null, "删除失败");
    } catch (error) {
      return this.handleResponse(null, error, null);
    }
  }

  async getOrdersByUserId(userId) {
    try {
      const orders = await OrdersPayRepository.getOrdersByUserId(userId);
      return this.handleResponse(orders, null, null);
    } catch (error) {
      return this.handleResponse(null, error, null);
    }
  }

  async getAllOrders() {
    try {
      const orders = await OrdersPayRepository.getAllOrders();
      return this.handleResponse(orders, null, null);
    } catch (error) {
      return this.handleResponse(null, error, null);
    }
  }

  async getLatestOrders(userId) {
     try {
       const orders = await OrdersPayRepository.getLatestOrders(userId);
       return this.handleResponse(orders, null, null);
     } catch (error) {
       return this.handleResponse(null, error, null);
     }
  }
}

module.exports = new OrdersPayService();
